﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Ctrip.Mobile.Services.Restful.Vacation.Services;
using CServiceStack.Common.Types;
using CServiceStack.ServiceHost;
using CServiceStack.WebHost.Endpoints;
using System.Collections.Specialized;
using System.Diagnostics;
using Newtonsoft.Json;
using System.Threading;

namespace SOAServiceCore
{
    public class IncomingHubAdpAttribute : Attribute, IHasRequestFilter
    {

        public string Name { get { return _innerHub.Name; } set { _innerHub.Name = value; } }
        public string Method { get { return _innerHub.Method; } set { _innerHub.Method = value; } }
        private IncomingHubAttribute _innerHub;

        public IncomingHubAdpAttribute()
            : base()
        {
            _innerHub = new IncomingHubAttribute();

        }
        public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            Trace.AutoFlush = true;
            Trace.WriteLine("incoming message adapter");
            //_innerHub.RequestFilter(req, res, requestDto);
        }

        public IHasRequestFilter Copy()
        {
            return _innerHub.Copy();
        }

        public int Priority
        {
            get { return _innerHub.Priority; }
        }
    }
    public class IncomingHubAttribute : Attribute, IHasRequestFilter
    {
        public string Name { get; set; }
        public string Method { get; set; }

        //public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        //{

        //}

        public IHasRequestFilter Copy()
        {
            return this;
        }

        public int Priority
        {
            get
            {
                return -1;
            }
        }


        public virtual void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(Method)) return;

            Trace.AutoFlush = true;
            Trace.WriteLine(string.Format("{0}:{1}", Method,
                       new
                       {
                           Time = DateTime.Now.ToString("G"),
                           Data = req.HttpMethod + " ," + req.RawUrl + ", " + req.GetRawBody()
                       }));
        }
    }

    public class OutgoingHubAttribute : Attribute, IHasResponseFilter
    {
        public string Name { get; set; }
        public string Method { get; set; }


        public IHasResponseFilter Copy()
        {
            return this;
        }

        public int Priority
        {
            get
            {
                return -1;
            }
        }





        public void ResponseFilter(IHttpRequest req, IHttpResponse res, object responseDto)
        {
            if (string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(Method)) return;
            Trace.AutoFlush = true;
            Trace.WriteLine(string.Format("{0}:{1}", Method, new { Time = DateTime.Now.ToString("G"), Data = responseDto }));
        }
    }

    //[IncomingHubAdp(Method = "GET", Name = "log")]
    //[OutgoingHub(Method = "GET", Name = "log")]
    public class H5VacationProductService : IH5VacationProductService
    {
        [Route("/Vacation/ProductList/Query", "GET")]
        [Hystrix(Timeout = 20000)]
        public ProductListSearchResponseType ProductListSearch(ProductListSearchRequestType request)
        {
            throw new Exception("catch me if u can");
            Random r = new Random(2);
            Thread.Sleep(r.Next(5) * 500);
            string responseBody = @"{""head"":{""auth"":null,""errcode"":0},""count"":9,""ext"":null,""filters"":[{""type"":1,""values"":[{""id"":"""",""name"":""不限"",""val"":0},{""id"":""1"",""name"":""1日"",""val"":2},{""id"":""2"",""name"":""2日"",""val"":2},{""id"":""3"",""name"":""3日"",""val"":1},{""id"":""4"",""name"":""4日"",""val"":1},{""id"":""5"",""name"":""5日"",""val"":3}]},{""type"":2,""values"":[{""id"":"""",""name"":""不限"",""val"":0},{""id"":""33"",""name"":""贵阳"",""val"":6},{""id"":""518"",""name"":""安顺"",""val"":4},{""id"":""10195"",""name"":""黄果树"",""val"":3},{""id"":""1770"",""name"":""赤水"",""val"":2},{""id"":""491"",""name"":""凯里"",""val"":2},{""id"":""204"",""name"":""遵义"",""val"":2},{""id"":""10111"",""name"":""西江苗寨"",""val"":2},{""id"":""521"",""name"":""毕节"",""val"":1}]},{""type"":3,""values"":[{""id"":"""",""name"":""不限"",""val"":0}]}],""flag"":0,""products"":[{""currency"":""RMB"",""dDateRmk"":""每周三"",""ext"":null,""flag"":0,""id"":1710176,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/33\/132x88\/33_15_132x88.jpg"",""name"":""贵州黄果树+西江苗寨5日团队游(3钻)·金海雪山赏花 当地游"",""prefFlag"":""代理"",""price"":1399,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""国家AAAAA级景区、亚洲第一大瀑布--黄果树！""},{""currency"":""RMB"",""dDateRmk"":""天天出发"",""ext"":null,""flag"":2,""id"":1730435,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/518\/132x88\/518_01_132x88.jpg"",""name"":""贵阳黄果树大瀑布、天星桥、陡坡塘纯玩一日游"",""prefFlag"":""代理"",""price"":398,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""为贵州旅游代言，全程绝无自费项目，包含景区环保车，真正一票到底！""},{""currency"":""RMB"",""dDateRmk"":""04\/03、04\/04..."",""ext"":null,""flag"":0,""id"":1749228,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/521\/132x88\/521_21_s22587_132x88.JPG"",""name"":""贵州黄果树+毕节+安顺5日当地参团(3钻)·百里杜鹃 赏花探洞乐趣多"",""prefFlag"":""代理"",""price"":1559,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""春游去哪里？南下赏花,‘地球的彩带、世界的花园’,畅游百里杜鹃花之乡！""},{""currency"":""RMB"",""dDateRmk"":""每周三、四"",""ext"":null,""flag"":0,""id"":1721541,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/33\/132x88\/33_03_132x88.jpg"",""name"":""贵州黄果树+西江苗寨5日团队游(3钻)·青岩古镇+天河潭 当地游"",""prefFlag"":""代理"",""price"":1550,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""精华景点一网打尽，精选酒店，让你旅途更加美满。""},{""currency"":""RMB"",""dDateRmk"":""每周二、三..."",""ext"":null,""flag"":0,""id"":1628147,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/33\/132x88\/33_277_s22587_132x88.JPG"",""name"":""贵州黄果树+贵阳4日团队游(4钻)·南江峡谷+青岩古镇 当地游"",""prefFlag"":null,""price"":1399,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":""早订优惠"",""subtitle"":""洗涤都市人浮躁的栖息地,与大自然邂逅,带给您完全不一样的体验！最高立减200!""},{""currency"":""RMB"",""dDateRmk"":""每周六"",""ext"":null,""flag"":0,""id"":1732936,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/1770\/132x88\/1770_14_s31519_132x88.JPG"",""name"":""贵州赤水2日当地参团(2钻)·游走世遗风光 早订爽"",""prefFlag"":""代理"",""price"":398,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":""早订优惠"",""subtitle"":""观无限自然风光！感受红军四渡赤水经历！""},{""currency"":""RMB"",""dDateRmk"":""每周五"",""ext"":null,""flag"":0,""id"":1734817,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/1770\/132x88\/1770_20_s38265_132x88.JPG"",""name"":""贵州遵义+赤水3日当地参团(2钻)·穿行世界遗产 早订优惠多"",""prefFlag"":""代理"",""price"":568,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""一座红色之城，让心灵去旅行，走近她的活色生香，感受她的山清水秀……遵义！""},{""currency"":""RMB"",""dDateRmk"":""每周六"",""ext"":null,""flag"":0,""id"":1743563,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/659\/132x88\/659_9_s30835_132x88.jpg"",""name"":""荔波+西江苗寨2日团队游(3钻)·贵州精华 超值特惠"",""prefFlag"":""代理"",""price"":538,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""观赏荔波小七孔自然风光！体验西江苗族风情文化！""},{""currency"":""RMB"",""dDateRmk"":""天天出发"",""ext"":null,""flag"":2,""id"":1730130,""imgUrls"":""http:\/\/pkgpic.ctrip.com\/images3\/1\/491\/132x88\/491_33_s22587_132x88.JPG"",""name"":""贵阳西江千户苗寨纯玩一日游"",""prefFlag"":""代理"",""price"":268,""prmt"":{""amt"":0,""currency"":""RMB"",""list"":[],""type"":0},""prmtDiscount"":0,""prmtRmk"":"""",""subtitle"":""游览中国乃至全世界最大的苗族聚居村寨，领略苗族漫长历史与发展的首选之地。""}]}";

            ProductListSearchResponseType response = JsonConvert.DeserializeObject<ProductListSearchResponseType>(responseBody);
            return response;//new ProductListSearchResponseType { head = new ResponseHead { errcode = 0 }, count = 1, ext = "ext", filters = new List<FilterItem> { new FilterItem { type = 1, values = new List<FilterValueItem> { new FilterValueItem { id = "2", name = "上海", val = "75" } } } }, products=new  };
        }

        public CheckHealthResponseType CheckHealth(CheckHealthRequestType request)
        {
            return new CheckHealthResponseType();
        }
    }
    public class RestAppHost : AppHostBase
    {
        public RestAppHost() : base(typeof(H5VacationProductService).Assembly) { }
        public override void Configure(Funq.Container container)
        {
            // 额外初始化
            //RequestFilters.Add((req, res, requestDto) =>
            //{
            //    NameValueCollection headers = req.Headers;

            //    Trace.AutoFlush = true;
            //    foreach (string h in headers.Keys)
            //    {
            //        Trace.WriteLine(string.Format("SOA: header:{0} value{1}", h, headers[h].ToString()));
            //    }

            //    Trace.WriteLine(string.Format("SOA: body{0}", req.GetRawBody()));
            //});
        }
    }
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            new RestAppHost().Init();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Response.Write(e);
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}